package com.liyunc.toolset;

/**
 * Copyright (c) 2018-2023 ThunderSoft
 * All Rights Reserved by Thunder Software Technology Co., Ltd and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with ThunderSoft in writing by applicable law.
 */

import com.liyunc.toolset.utils.ArgUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liyuncong
 * @version 1.0
 * @file Processor
 * @brief Processor
 * @details Processor
 * @date 2023-02-16
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2023-02-16                  liyuncong          Created
 */
public class Processor {

    public static final String FIND_ALL_PID = "adb -s a977c21a shell ls /proc";
    public static final String CAT_CMD = "adb -s a977c21a shell cat /proc/%s/cmdline";


    public static int[] searchProcess(SearchMode mode, String pattern) {
        System.out.println("pid list");
        getAllPids().forEach(System.out::println);
        return new int[] {};
    }

    public static List<String> getAllPids() {
        List<String> pids = new ArrayList<>();
        try {
            Process process = Runtime.getRuntime().exec(FIND_ALL_PID);

            BufferedReader input =
                new BufferedReader(new InputStreamReader(process.getInputStream()));

            String pid;
            while ((pid = input.readLine()) != null) {
                if (ArgUtils.isNumber(pid)) {
                    System.out.println("pid : " + pid);
                    System.out.println("cmdline : " + catCmdline(pid));
                    pids.add(pid);
                }
            }
            input.close();
        } catch (Exception ex) {
            throw new RuntimeException("Get open process exception", ex);
        }
        return pids;
    }

    public static String catCmdline(String pid) {
        try {
            Process process = Runtime.getRuntime().exec(String.format(CAT_CMD, pid));
            BufferedReader input =
                new BufferedReader(new InputStreamReader(process.getInputStream()));
            return input.readLine();
        } catch (Exception ex) {
            return "error";
        }
    }

}
